<template>
  <input 
    ref="inputRef"
    class="px-1 py-0 text-[12px] leading-[22px] h-[22px] rounded outline-none border-0 focus:ring-1 focus:ring-blue-500/40 bg-white dark:bg-neutral-800 w-[220px] shadow-inner"
    :value="editingLabel"
    @input="$emit('update:label', $event.target.value)"
    :placeholder="placeholder"
    @keydown.enter.stop.prevent="onCommit"
    @keydown.esc.stop.prevent="onCancel"
    @blur="onCommit"
  />
</template>

<script setup>
import { computed, ref, onMounted, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

// Props
const props = defineProps({
  editingMode: { type: String, required: true }, // 'new-folder', 'new-file', 'rename'
  editingLabel: { type: String, default: '' },
  autoFocus: { type: Boolean, default: true },
  autoSelect: { type: Boolean, default: true },
});

// Events
const emit = defineEmits([
  'commit',
  'cancel',
  'update:label',
  'set-input'
]);

// Refs
const inputRef = ref(null);

// 计算属性
const placeholder = computed(() => {
  switch (props.editingMode) {
    case 'new-folder':
      return t('explorer.new_folder_placeholder') || 'New Folder';
    case 'new-file':
      return t('explorer.new_file_placeholder') || 'New File';
    case 'rename':
    default:
      return t('explorer.rename_placeholder') || 'Rename';
  }
});

// 方法
function onCommit() {
  if (props.editingLabel.trim()) {
    emit('commit');
  } else {
    emit('cancel');
  }
}

function onCancel() {
  emit('cancel');
}

function focusAndSelect() {
  if (inputRef.value) {
    inputRef.value.focus();
    if (props.autoSelect) {
      // 如果是重命名模式，选中文件名部分（不包括扩展名）
      if (props.editingMode === 'rename' && props.editingLabel.includes('.')) {
        const lastDotIndex = props.editingLabel.lastIndexOf('.');
        inputRef.value.setSelectionRange(0, lastDotIndex);
      } else {
        inputRef.value.select();
      }
    }
  }
}

// 生命周期
onMounted(async () => {
  if (props.autoFocus) {
    await nextTick();
    focusAndSelect();
    // 通知父组件输入框已准备好
    emit('set-input', inputRef.value);
  }
});

// 暴露方法给父组件
defineExpose({
  focus: focusAndSelect,
  blur: () => inputRef.value?.blur(),
  getInputElement: () => inputRef.value
});
</script>

<style scoped>
/* 输入框样式已在template中定义 */
</style>